package com.fwtai.quartz;

import com.fwtai.pay.wechat.ToolWechat;
import com.fwtai.pay.wechat.WechatPayConstants;
import com.fwtai.service.SpringContextHolder;
import com.fwtai.service.api.ApiGoodsOrderService;
import com.fwtai.tool.ToolClient;
import com.fwtai.tool.ToolOkHttp;
import com.fwtai.tool.ToolString;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.TriggerKey;
import org.quartz.impl.StdSchedulerFactory;

import java.util.HashMap;

/**
 * Quartz工具类
 * @作者 田应平
 * @版本 v1.0
 * @创建时间 2023-12-29 18:04:03
 * @QQ号码 444141300
 * @Email service@fwtai.com
 * @官网 <url>http://www.fwtai.com</url>
*/
public final class ToolQuartz{

  private volatile static ToolQuartz INSTANCE;

  private ToolQuartz(){}

  public static ToolQuartz getInstance(){
    if(INSTANCE == null){
      synchronized(ToolQuartz.class){
        if(INSTANCE == null){
          INSTANCE = new ToolQuartz();
        }
      }
    }
    return INSTANCE;
  }

  //移除一个任务,jobName和groupName必须是唯一
  public static void deleteJob(final String jobName,final String groupName){
    try {
      final Scheduler scheduler = new StdSchedulerFactory().getScheduler();//创建调度器Scheduler
      final TriggerKey triggerKey = new TriggerKey(jobName,groupName);
      scheduler.pauseTrigger(triggerKey);//停止指定的name和group的触发器
      scheduler.unscheduleJob(triggerKey);//移除触发器
      scheduler.deleteJob(new JobKey(jobName,groupName));//删除任务,判断是否删除任务成功，final JobDetail jobDetail = scheduler.getJobDetail(new JobKey(jobName,groupName));
    } catch (final SchedulerException exception){
      exception.printStackTrace();
    }
  }

  /*仅支持微信购买支付的订单才需要执行本方法`查询微信服务器的订单收货状态`*/
  public static void editDelayedResult(final String transactionId,final long out_trade_no,final String type){
    try {
      HashMap<String,String> map = queryOrder(transactionId);
      if("0".equals(map.get("errcode"))){
        final String order = map.get("order");
        final HashMap<String,String> hashMap = ToolString.parseJsonObject(order);
        final String state = hashMap.get("order_state");
        switch (state){//订单状态枚举：(1) 待发货；(2) 已发货；(3) 确认收货；(4) 交易完成；(5) 已退款。
          case "3":
          case "4":
            SpringContextHolder.getBean(ApiGoodsOrderService.class).editDelivery(out_trade_no,type);
            break;
          default:
            break;
        }
      }
    } catch (final Exception exception){
      exception.printStackTrace();
    }
  }

  public static void editAffirmResult(final String transactionId,final long out_trade_no){
    try {
      HashMap<String,String> map = queryOrder(transactionId);
      if("0".equals(map.get("errcode"))){
        final String order = map.get("order");
        final HashMap<String,String> hashMap = ToolString.parseJsonObject(order);
        final String state = hashMap.get("order_state");
        switch (state){//订单状态枚举：(1) 待发货；(2) 已发货；(3) 确认收货；(4) 交易完成；(5) 已退款。
          case "3":
          case "4":
            SpringContextHolder.getBean(ApiGoodsOrderService.class).editAffirm(out_trade_no);
            break;
          default:
            break;
        }
      }
    } catch (final Exception exception){
      exception.printStackTrace();
    }
  }

  private static HashMap<String,String> queryOrder(final String transactionId) throws Exception{
    final String accessToken = ToolWechat.getAccessToken(WechatPayConstants.APP_ID,WechatPayConstants.SECRET);
    final HashMap<String,Object> params = new HashMap<>(1);
    params.put("transaction_id",transactionId);
    final String url = "https://api.weixin.qq.com/wxa/sec/order/get_order?access_token=" + accessToken;
    final String jsonRequest = ToolOkHttp.postSync(url,ToolClient.toJson(params));
    return ToolString.parseJsonObject(jsonRequest);
  }
}